package holdem.network;

import holdem.Player;

//~--- imports: JDK -----------------------------------------------------------

import java.io.*;

import java.net.Socket;

public class ClientHandler implements Runnable
{
    private int                playerID;
    public Player player;
    private Socket             so;
    private ObjectInputStream  streamIn;
    private ObjectOutputStream streamOut;

    //~--- constructors -------------------------------------------------------

    public ClientHandler(Socket s, int playerID) throws IOException
    {
	so        = s;
        this.playerID = playerID;
	streamOut = new ObjectOutputStream(so.getOutputStream());
	streamIn  = new ObjectInputStream(so.getInputStream());
    }

    //~--- methods ------------------------------------------------------------

    public synchronized void sendMessage(NetworkEvent e) throws IOException
    {
        if(Server.debugMode) {
            System.out.println("[Msg]server -> " + playerID + ": " + e);
        }
	streamOut.writeObject(e);
    }

    @Override
    protected void finalize() throws Throwable
    {
        System.out.println(so.getInetAddress().getHostName()+" disconnected");
	super.finalize();
	streamIn.close();
	streamOut.close();
	so.close();
    }

    public int getPlayerID()
    {
        return playerID;
    }

    public void run()
    {
	System.out.println("New pipe online.");
	
        //new listening thread.
        new StreamInThread(streamIn, playerID);
    }
}


class StreamInThread implements Runnable
{
    Thread runner;
    ObjectInputStream streamIn;
    private int playerID;

    public StreamInThread(ObjectInputStream streamIn, int playerID)
    {
        runner = new Thread(this);
        this.streamIn = streamIn;
        this.playerID = playerID;
        runner.start();
    }

    public void run()
    {
        System.out.println(Thread.currentThread());
        while (true) {
            try {
                NetworkRequest cmd = (NetworkRequest) streamIn.readObject();
                cmd.setPlayerID(playerID);
                if(Server.debugMode) {
                    System.out.println("[Req]" + playerID + " -> " + "server: " + cmd);
                }
                //thread player
                //check palyer if its your turn
                //if (Server.dealer.getTurn() == playerID)
                    cmd.event(Server.dealer);
            } catch (IOException e) {
                break;
            } catch (ClassNotFoundException e) {
                throw new Error(e);
            }
        }

    }
}

